package com.ltu.config.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ltu.enums.MqTopiceDict;
import com.ltu.service.mqtt.MqttListenterTopic;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Configuration
@EnableConfigurationProperties(MqttProperties.class)
public class MqttConfiguration {
	 private MqttProperties mqttProperties;

    public MqttConfiguration() {
		super();
		// TODO Auto-generated constructor stub
	}
    @Autowired
    public MqttConfiguration(MqttProperties mqttProperties) {
    	this.mqttProperties=mqttProperties;
    }

	/**
     * 客户端连接
     * @param host      ip+端口
     * @param clientID  客户端Id
     * @param username  用户名
     * @param password  密码
     * @param timeout   超时时间
     * @param keeplive 保留数
     */
    @Bean(name = "mqttClient")
    public MqttClient connect(@Autowired  MqttListenterTopic mqttListenterTopic){
        MqttClient client=null; 
        //MqttAsyncClient 
        try {
            client=new MqttClient(this.mqttProperties.getHost(),this.mqttProperties.getClientid(),new MemoryPersistence());
            
            MqttConnectOptions options=new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(this.mqttProperties.getUsername());
            options.setPassword(this.mqttProperties.getPassword().toCharArray());
            options.setConnectionTimeout(this.mqttProperties.getTimeout());
            options.setKeepAliveInterval(this.mqttProperties.getKeepalive());
            options.setAutomaticReconnect(true); //设置重连
            client.setCallback(mqttListenterTopic);
            try {
            	if(!client.isConnected())
            		 client.connect(options);
            	this.subscribe(client);
            }catch (MqttException e){
                e.printStackTrace();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return client;
    }
    
    private  void  subscribe(MqttClient client) {
    	try {
    		//订阅延迟主题
    		client.subscribe(MqTopiceDict.OrderEnum.OrderPayListen.getValue(),0);
//    		client.subscribe(MqTopiceDict.OrderEnum.Disconnected.getDesc(),0);
//    		client.subscribe(MqTopiceDict.OrderEnum.Connected.getDesc(),1);
    		log.info("========== 连接EMQX服务成功 ====================");
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
    /**
     * 取消订阅某个主题
     *
     * @param topic
     */
    public void unsubscribe(MqttClient client,String topic) {
        log.info("==============取消订阅主题==============" + topic);
        try {
            client.unsubscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}